const {
	insertSqlPublic,
	getMysqlPage,
	currentDate
} = require('./global')
const db = require('../db/index')


// 查询兑换列表
exports.getList = async (req, res) => {
	try {
		// 等待从连接池中获取一个连接
		const connection = await db.getConnection();
		try {
			const { keywords = "", status = "", openid = "" } = req.query;
			let sql = `
				SELECT 
					tb1.*, tb3.name clientName, tb3.phone clientPhone, tb3.city clientCity, tb3.detail clientDetail, tb2.name ownerName,
					CASE
						WHEN tb1.status = 0 THEN '审核中'
						WHEN tb1.status = 1 THEN '已发货'
						WHEN tb1.status = -1 THEN '审核失败'
					END statusName,
					CASE
						WHEN tb1.status = 0 THEN 'primary'
						WHEN tb1.status = 1 THEN 'success'
						WHEN tb1.status = -1 THEN 'error'
					END statusType
				FROM cc_exchange tb1 
				LEFT JOIN 
					cc_user tb2 
				ON tb1.openid = tb2.openid
				LEFT JOIN 
					cc_address tb3 
				ON tb3.id = tb1.address_id				
				`;
			// console.log(sql)
			let whereClause = [], fields = [];
			if (status && status != 99) {
				whereClause.push("tb1.status = ?");
				fields.push(status)
			}
			// 如果传了openid
			if (openid) {
				whereClause.push("tb1.openid = ?");
				fields.push(openid)
			}
			if (keywords) {
				whereClause.push("(tb1.code LIKE ? OR tb3.name LIKE ? OR tb3.phone LIKE ?)");
				fields.push('%' + keywords + '%');
				fields.push('%' + keywords + '%');
				fields.push('%' + keywords + '%');
			}
			if (whereClause.length === 1) {
				sql += ' WHERE ' + whereClause[0];
			}
			if (whereClause.length > 1) {
				sql += ' WHERE ' + whereClause.join(' AND ');
			}
			sql += ` ORDER BY 
					tb1.ent_date desc`
			const rows = await getMysqlPage(sql, fields, req.query);

			res.json({
				status: 200,
				message: '成功',
				data: rows
			});
		} catch (e) {
			console.error('Query error:', e);
			res.status(500).json({
				status: 500,
				message: e.message
			});
		} finally {
			// 无论查询是否成功，都释放连接
			connection.release();
		}
	} catch (err) {
		console.error('Database connection error:', err);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	}
}


//新增
exports.addExchange = async (req, res) => {
	try {
		// 等待从连接池中获取一个连接
		const connection = await db.getConnection();
		try {
			const params = req.body;
			// console.log(params)
			const sql = await insertSqlPublic('cc_exchange', 'crab_card', params, null);

			// 执行 SQL 语句
			const [rows] = await connection.execute(sql);
			if (rows.affectedRows === 1) {
				res.json({ // 使用 201 表示 Created
					status: 200,
					message: '成功',
					data: rows
				});
			} else {
				res.status(400).json({ // 使用 400 表示 Bad Request
					status: 400,
					message: '插入失败'
				});
			}
		} catch (e) {
			console.error('Query error:', e);
			res.status(500).json({
				status: 500,
				message: e.message
			});
		} finally {
			// 无论查询是否成功，都释放连接
			connection.release();
		}
	} catch (err) {
		console.error('Database connection error:', err);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	}
};



//修改
exports.editExchange = async (req, res) => {
	try {
		// 等待从连接池中获取一个连接
		const connection = await db.getConnection();
		try {
			const params = req.body;
			// console.log(params)
			let fields = [params.status, currentDate(), params.id]
			let sql = "update cc_exchange set status = ?, check_date = ?";
			if (params.status === 1) { // 如果是审核通过并发货，则需要更新物流相关字段
				sql += `, send_code = ?, send_date = ?`
				fields.splice(fields.length - 1, 0, params.send_code, params.send_date)
			}
			if (params.status === -1) { // 如果是审核不通过，则需要更新拒绝理由
				sql += `, reject_reason = ?`
				fields.splice(fields.length - 1, 0, params.reject_reason)
			}
			sql += " WHERE id = ?"

			// 执行 SQL 语句
			const [rows] = await connection.execute(sql, fields);
			if (rows.affectedRows === 1) {
				res.json({ // 使用 201 表示 Created
					status: 200,
					message: '修改成功',
					data: rows
				});
			} else {
				res.status(400).json({ // 使用 400 表示 Bad Request
					status: 400,
					message: '修改失败'
				});
			}
		} catch (e) {
			console.error('Query error:', e);
			res.status(500).json({
				status: 500,
				message: e.message
			});
		} finally {
			// 无论查询是否成功，都释放连接
			connection.release();
		}
	} catch (err) {
		console.error('Database connection error:', err);
		res.status(500).json({
			status: 500,
			message: '数据库连接错误'
		});
	}
};